package com.gpt.article.controller;

import java.io.*;
import java.util.Base64;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import com.document.PptToHtml;
import com.document.TxtToHtml;
import com.document.WordToHtml;
import com.document.pdfdoms.CreatePdfHtml;
import com.gpt.article.domain.GptSpiderArticle;
import com.gpt.article.domain.GptSpiderArticleContent;
import com.gpt.article.service.IGptSpiderArticleContentService;
import com.gpt.article.service.IGptSpiderArticleService;
import com.gpt.article.service.impl.GptSpiderDiyServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.ZipUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.gpt.article.domain.GptSysFile;
import com.gpt.article.service.IGptSysFileService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.framework.config.ServerConfig;
/**
 * 采集文件Controller
 * 
 * @author zhuzi
 * @date 2023-10-31
 */
@RestController
@RequestMapping("/article/file")
public class GptSysFileController extends BaseController
{
    @Autowired
    private IGptSysFileService gptSysFileService;
    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IGptSpiderArticleService gptSpiderArticleService;
    @Autowired
    private IGptSpiderArticleContentService gptSpiderArticleContentService;

    /**
     * 查询采集文件列表
     */
    @PreAuthorize("@ss.hasPermi('article:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(GptSysFile gptSysFile)
    {
        startPage();
        List<GptSysFile> list = gptSysFileService.selectGptSysFileList(gptSysFile);
        return getDataTable(list);
    }

    /**
     * 导出采集文件列表
     */
    @PreAuthorize("@ss.hasPermi('article:file:export')")
    @Log(title = "采集文件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GptSysFile gptSysFile)
    {
        List<GptSysFile> list = gptSysFileService.selectGptSysFileList(gptSysFile);
        ExcelUtil<GptSysFile> util = new ExcelUtil<GptSysFile>(GptSysFile.class);
        util.exportExcel(response, list, "采集文件数据");
    }

    /**
     * 获取采集文件详细信息
     */
    @PreAuthorize("@ss.hasPermi('article:file:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(gptSysFileService.selectGptSysFileById(id));
    }

    /**
     * 新增采集文件
     */
    @PreAuthorize("@ss.hasPermi('article:file:add')")
    @Log(title = "采集文件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GptSysFile gptSysFile)
    {
        return toAjax(gptSysFileService.insertGptSysFile(gptSysFile));
    }

    /**
     * 修改采集文件
     */
    @PreAuthorize("@ss.hasPermi('article:file:edit')")
    @Log(title = "采集文件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GptSysFile gptSysFile)
    {
        return toAjax(gptSysFileService.updateGptSysFile(gptSysFile));
    }

    /**
     * 删除采集文件
     */
    @PreAuthorize("@ss.hasPermi('article:file:remove')")
    @Log(title = "采集文件", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(gptSysFileService.deleteGptSysFileByIds(ids));
    }


    /**
     * 洗图
     */
    @PreAuthorize("@ss.hasPermi('article:file:add')")
    @Log(title = "洗图", businessType = BusinessType.XITU)
    @GetMapping("/xituStart/{ids}")
    public AjaxResult xituStart(@PathVariable Long[] ids)
    {
        List<String> urlList = gptSysFileService.xituStart(ids);
        return toAjax(urlList.size()>0);
    }

    /**
     * 上传数据包
     * @param file
     * @return
     * @throws Exception
     */
    @Log(title = "上传数据包", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file,String classId,String className,String promptsId,String promptsName,String sourceId,String sourceName) throws Exception
    {

        String operName = getUsername();


        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String fileExt = FileUtil.extName(fileName);
        if(!"zip".equals(fileExt)){
            AjaxResult ajax = AjaxResult.error("不支持的格式："+fileExt);
            return ajax;
        }

        String url = serverConfig.getUrl() + fileName;
        AjaxResult ajax = AjaxResult.success();
        ajax.put("url", url);
        ajax.put("fileName", fileName);
        ajax.put("newFileName", FileUtils.getName(fileName));
        ajax.put("originalFilename", file.getOriginalFilename());
        System.out.println(filePath+"/"+fileName);
        //解析文件
        System.out.println(filePath+"--");
        String unzipPath = filePath+fileName.replaceAll("/profile/upload","");
        System.out.println(unzipPath);
//        /profile/upload/2023/11/13/template_20231113211439A003.zip
        String zipDirectoryPath = unzipPath.substring(0,
                unzipPath.lastIndexOf("."));
        //解压第一层包
        ZipUtils.unzip2(new File(unzipPath),zipDirectoryPath);
        System.out.println(zipDirectoryPath+"====");
        File[] files = new File(zipDirectoryPath).listFiles();

        // 上传文件路径
        String savePaperImgPath = RuoYiConfig.getUploadPath()+"/"+ FileUtils.getDateFilePath();

        for(File f:files){
            System.out.println(f.getName());
            String htmlPath = "";
            try{
                htmlPath =  Office2Html(f);
            }catch (Exception e){
                logger.error(e.getMessage());
            }

            if(StringUtils.isEmpty(htmlPath)){
                logger.error("出现不支持解析的数据格式，检查数据包..");
                continue;
            }
            String title = FileUtil.mainName(f);
            String htmlcontent = readHTMLFile(htmlPath);
            Document document = Jsoup.parse(htmlcontent);
            List<Element> newsImgList = document.getElementsByTag("img");
            String md5str = DateUtils.dateTimeNow()+title;
            String urlMd5 = Md5Utils.hash(md5str);
            int imgNo = 0;
            GptSysFile gptSysFile  =null;
            String imgMd5 = "";
            for (Element imgEl : newsImgList) {
                String md5ps =DateUtils.dateTimeNow()+imgNo;
                imgMd5 = Md5Utils.hash(md5ps);

                String paperimgName = imgMd5+ ".jpg";
                String base64str= imgEl.attr("src");
                base64ToJpg(savePaperImgPath,base64str,imgMd5);
                //保存图
                String saveName = title+"-第"+imgNo+"张图";
                String newImg = savePaperImgPath+paperimgName;
                File newFile = new File(newImg);
                gptSysFile  =  new GptSysFile();
                gptSysFile.setDir(FileUtils.getDateFilePath());
                gptSysFile.setName(saveName);
                gptSysFile.setSizes(FileUtils.GetFileSize(newFile));
                gptSysFile.setUserId("admin");
                gptSysFile.setUserName("管理员");
                gptSysFile.setArtTitle(title);
                gptSysFile.setXitustatus("0");
                gptSysFile.setUrlMd5(urlMd5);
                gptSysFile.setImgmd5(imgMd5);
                gptSysFile.setOrderNo(imgNo);
                try {
                    gptSysFileService.insertGptSysFile(gptSysFile);
                }catch (Exception e){
                    System.out.println("图片已存在无需保存："+e.getMessage());
                }
                // 重新赋值img路径
                String newsDetailImg = "/dev-api/profile/upload/" +FileUtils.getDateFilePath()+ paperimgName;
                imgEl.attr("src", newsDetailImg);
                imgNo++;
            }
            String artConetnt = document.toString();

            System.out.println("urlMd5:::::"+urlMd5);
            artConetnt= artConetnt.replaceAll("\"(.*?)http(.*?)\"","'#'");
            artConetnt= artConetnt.replaceAll("\'(.*?)http(.*?)\'","'#'");
            artConetnt= artConetnt.replaceAll("\"(.*?)https(.*?)\"","'#'");
            artConetnt= artConetnt.replaceAll("\'(.*?)https(.*?)\'","'#'");
            artConetnt= GptSpiderDiyServiceImpl.delHtmlTags(artConetnt);
            GptSpiderArticleContent gptSpiderArticleContent  = new GptSpiderArticleContent();
            gptSpiderArticleContent.setUrlMd5(urlMd5);
            gptSpiderArticleContent.setArtContent(artConetnt);
            long contentId = 1l;
            try {
                contentId = gptSpiderArticleContentService.insertGptSpiderArticleContent(gptSpiderArticleContent);
            }catch (Exception e){
                System.out.println("文章内容已存在无需保存："+e.getMessage());
            }

            GptSpiderArticle gptSpiderArticle = new GptSpiderArticle();
            gptSpiderArticle.setTitle(title);
            gptSpiderArticle.setPromptsId(Long.valueOf(promptsId));
            gptSpiderArticle.setPromptsName(promptsName);
//            gptSpiderArticle.setSpiderDiyId(diy.getId());
//            gptSpiderArticle.setSpiderDiyName(diy.getName());
            gptSpiderArticle.setContentId(contentId);
            gptSpiderArticle.setUrlMd5(urlMd5);
            gptSpiderArticle.setClassId(Integer.valueOf(classId));
            gptSpiderArticle.setClassName(className);
            gptSpiderArticle.setSourceId(Long.valueOf(sourceId));
            gptSpiderArticle.setSourceName(sourceName);
            gptSpiderArticle.setStatus("0");
            gptSpiderArticle.setSpiderUrl(null);
            try {
                gptSpiderArticleService.insertGptSpiderArticle(gptSpiderArticle);
            }catch (Exception e){
                System.out.println("文章已存在无需保存："+e.getMessage());
            }
//            Long sourceId = 3l;
//            String sourceName = "本平台";

        }


        return success("成功");
    }


    public static  String Office2Html(File file) throws Exception {
        String extName = FileUtil.extName(file);
        String htmlPathWidthName = file.getAbsolutePath().replaceAll(extName,"")+"html";
        System.out.println("格式：{}"+extName+"，转化文件路径名:{}"+htmlPathWidthName+",源文件：{}"+file.getAbsolutePath());
        switch (extName){
            case "doc":
                WordToHtml.convertDocFileToHtml(file.getAbsolutePath(),htmlPathWidthName);
                break;
            case "pdf":
                CreatePdfHtml.createHtmlPage(file.getAbsolutePath(),htmlPathWidthName);
                break;
            case "docx":
                WordToHtml.convertDocxFileToHtml(file.getAbsolutePath(),htmlPathWidthName);
                break;
            case "pptx":
                new PptToHtml().pptToHtml(file.getAbsolutePath(),htmlPathWidthName);
                break;
            case "txt":
                TxtToHtml.txtToHtml(file.getAbsolutePath(),htmlPathWidthName);
                break;
            default:
                return null;
        }

        return htmlPathWidthName;
    }

    /**
     * 读取html内容
     * @param filePath
     * @return
     */
    public static String readHTMLFile(String filePath) {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }


    /**
     * base64转为图片
     * @param path
     * 文件路径：到文件夹即可，代码里会在文件夹里生成对应的jpg文件
     * @param base64
     * @return
     */
    public static String base64ToJpg(String path,String base64,String fileName){
        // 判断文件路径是否存在
        File filePath = new File(path);
        if (!filePath.exists()){
            filePath.mkdirs();
        }
        // 创建文件
        String jpgFile = path + "\\" + fileName + ".jpg";
        File file = new File(jpgFile);
        boolean jpgFileExist = false;
        try {
            jpgFileExist = file.createNewFile();
            System.out.println("jpg文件创建成功");
        } catch (IOException e) {
            System.out.println("jpg文件创建失败");
            e.printStackTrace();
        }
        if (jpgFileExist){
            // 解密
            Base64.Decoder decoder = Base64.getDecoder();
            // 去掉base64前缀 data:image/jpeg;base64,
            base64 = base64.substring(base64.indexOf(",", 1) + 1, base64.length());
            byte[] b = decoder.decode(base64);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 保存图片
            try {
                FileOutputStream out = new FileOutputStream(jpgFile);
                out.write(b);
                out.flush();
                out.close();
                // 写入成功返回文件路径
                return jpgFile;
            } catch (FileNotFoundException e) {
                System.out.println("文件未找到");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("写入失败");
                e.printStackTrace();
            }
        }
        return "文件不存在";
    }



}
